package com.ev.common.jobs;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ev.custom.domain.DeviceDO;
import com.ev.custom.service.DeviceService;
import com.ev.custom.service.InfluxService;
import com.ev.framework.utils.DateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;

@Slf4j
@Component
public class MeasurementJob implements Job {

    @Autowired
    private InfluxService influxService;

    @Autowired
    private DeviceService deviceService;

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        sendOutPut();
    }

    /**
     * 获取所有设备的产量数据
     */
    private void sendOutPut() throws ParseException{
        Map<String,Object> params = new HashMap<>();
        params.put("useType",156);
        List<DeviceDO> deviceDOList = deviceService.list(params);
        Long[] pointIds = deviceDOList.stream().map(DeviceDO::getMeasurementId).filter(Objects::nonNull).toArray(Long[]::new);
        String now = DateUtils.format(new Date(),DateUtils.DATE_PATTERN);
        String startTime = now+" 00:00:00";
        String endTime = now+" 23:59:59";
        JSONArray output = influxService.output(startTime, endTime, pointIds);
        for(int i=0;i<output.size();i++){
            JSONObject object = output.getJSONObject(i);
            for(DeviceDO deviceDO : deviceDOList){
//                Long pointId = object.getLong("pointId");
//                if (pointId == null){
//                    continue;
//                }
                if(deviceDO.getMeasurementId() != null
                        &&deviceDO.getMeasurementId().compareTo(object.getLong("pointId"))==0){
                    object.put("deviceId",deviceDO.getId());
                }
            }
        }
        // TODO 海达尔产量json
        //CusWebSocket.sendInfo("{\"dailyOutPut\":"+ JSON.toJSONString(output) +"}");

    }
}
